package de.lulusoft.anothertorrent.gui.util;

import java.text.DecimalFormat;

public class Util {

	/**
	 * Formats a Long value to the corresponding b, mb.. 
	 * Uses two trailing numbers..
	 * @param bytes
	 * @return
	 */
	public static String formatBytes(Long bytes)
	{
		if (bytes == 0) 
			return "";
	    String[] sizes = {"B","KB","MB","GB","TB","PB"};
	    DecimalFormat format = new DecimalFormat("#.##");
	    int selected = 0;
	    Double d = (double)bytes;
	    while (d >= 1024) 
	    {
	        selected++;
	        d = d / 1024;
	    }
	    return format.format(d) + " " + sizes[selected];
	}
	
	public static String formatSeconds(Long seconds)
	{
		if (seconds == 0)
			return "";
		else if (seconds == Long.MAX_VALUE)
			return "infinite";
		String[] sizes = {"s","m","h","d"};
		int selected = 0;
	    Double d = (double)seconds;
	    if (d > 60)
	    {
	    	selected++;
	    	d = d / 60;
	    }
	    if (d > 60)
	    {
	    	selected++;
	    	d = d / 60;
	    }
	    if (d > 24)
	    {
	    	selected++;
	    	d = d / 24;
	    }
	    return d.intValue() + " " + sizes[selected];
	}
	
	public static String formatBoolean(Long val)
	{
		if (val == 0L)
			return "No";
		return "Yes";
	}
	
	public static String convertBytesToHex(byte b[])
	{
		String result = "";
		for (int i=0; i < b.length; i++) 
		{
			result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
		}
		return result;
	}
	
	public static byte[] convertHexStringToBytes(String hex)
	{
		if ((hex.length() == 0) || (hex.length() % 2 != 0))
			return null;
		byte retval[] = new byte[hex.length() / 2];
		for (int i = 0; i < retval.length; i++)
		{
			retval[i] = (byte)Integer.parseInt(hex.substring(i*2, i*2+2), 16);
		}
		return retval;
	}
}
